/**
 * 
 */
package com.ssm.web.controller;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ssm.entity.Book;
import com.ssm.enums.AppointStateEnum;
import com.ssm.exception.AppointExecution;
import com.ssm.exception.NonumberException;
import com.ssm.exception.ReaptAppointException;
import com.ssm.service.BookService;
import com.ssm.web.Json.JsonResult;

/**
 * @author xieqiang_daye
 *
 */
@Controller
@RequestMapping("/book")//url:/模块/资源/{id}/细分/seckill/list
public class HelloController {
   
	private Logger log = LoggerFactory.getLogger(HelloController.class);
	
	@Autowired
	private BookService bookService;
	
	@RequestMapping(value="/list",method=RequestMethod.GET)
	public String list(Model model){
		List<Book> list = bookService.getList();
		model.addAttribute("list",list);//list.jsp+model=ModelAndView
		return "list";
	}
	
	@RequestMapping(value="/{bookId}/detail",method=RequestMethod.GET)
	public String detail(@PathVariable("bookId") Long bookId,Model model){
		if(bookId==null){
			return "redirect:/book/list";
		}
		Book book = bookService.getById(bookId);
		if(book==null){
			return "forward:/book/list";
		}
		model.addAttribute("book", book);
		return "detail";
	}
	
	//返回json值
	
	@RequestMapping(value="/{bookId}/appoint",method=RequestMethod.POST,
			produces={"application/json;charset=utf-8"})
	@ResponseBody
	public JsonResult appoint(@PathVariable("bookId") Long bookId,@RequestParam("studentId") Long studentId){
		if(studentId==null){
			return new JsonResult(false,"学号不能为空");
		}
		AppointExecution execution = null;
		try{
			execution = bookService.appoint(bookId, studentId);
		}catch(NonumberException e1){
			execution = new AppointExecution(bookId, AppointStateEnum.NO_NUMBER);
		}catch(ReaptAppointException e2){
			execution = new AppointExecution(bookId, AppointStateEnum.REPEAT_APPOINT);
		}catch(Exception e3){
			execution = new AppointExecution(bookId, AppointStateEnum.INNER_ERROE);
		}
		return new JsonResult(true, execution);
	}
}
